import { page, pageFunc } from "../common/PageBuilder";
import { ItemDetailPage } from "../common/pages/ItemDetailPage";
import { Exam, examRepo } from "../../modules/examModule/data/Exam";
import { UserPage } from "../common/partPages/UserPage";
import { alertMgr, handleError } from "../../modules/coreModule/managers/AlertManager";
import { waitForLogin } from "../../modules/userModule/managers/UserManager";
import { waitForDataLoad } from "../../modules/coreModule/managers/DataManager";
import { quesRepo, Question } from "../../modules/examModule/data/Question";
import { ExamInterface } from "../../modules/examModule/ExamCommon";
import { BasePageData } from "../common/core/BasePage";
import { field } from "../../modules/coreModule/data/DataLoader";
import { InstructorLevel } from "../../modules/userModule/data/Role";
import { BaseData, PK, pkType } from "../../modules/coreModule/data/BaseData";
import { pageMgr } from "../../modules/coreModule/managers/PageManager";
import {TemplateIds} from "../../modules/messageModule/MessageCommon";

class QuesRecord extends BaseData {
	@field(pkType())
	questionId: PK
	@field(String)
	content: string
	@field(Number)
	time: number
}

class Data extends BasePageData {

	@field(Exam)
	item: Exam;
	@field(InstructorLevel)
	level: InstructorLevel;
	@field([Question])
	quesList: Question[] = [];
	@field([QuesRecord])
	quesRecords: QuesRecord[] = [];
	@field(Number)
	currentIndex: number = 0;
	@field(String)
	currentResult: string = "";
	@field
	time: number = 0; // 考试时间
	@field
	show: boolean = false; // 控制弹出框的显示
}

class Param {
	examId: PK
	questionIds: PK[]
	examRecordId: PK
}

@page("question", "考试中")
export class QuestionPage extends ItemDetailPage<Data, Exam, Param> {

	public data = new Data();

	/**
	 * 部分页
	 */
	public userPage: UserPage = new UserPage(false, true);

	onLoad(e) {
		super.onLoad(e);
		this.loadData().then();
	}

	@handleError
	@waitForLogin
	@waitForDataLoad
	private async loadData() {
		const exam = examRepo().doc(this.params.examId);
		const quesList = this.params.questionIds.map(qid => quesRepo().doc(qid));

		// const res = await ExamInterface.StartExam({examId: exam._id});
		// const qids = res.questionIds;
		//
		// const quesList = qids.map(qid => quesRepo().doc(qid));

		return this.setData({
			item: exam, level: exam.level, quesList,
			time: exam.time, currentIndex: 0,
			quesRecords: this.makeQuesRecords(quesList)
		});
	}
	private makeQuesRecords(quesList: Question[]): QuesRecord[] {
		return quesList.map(q => ({
			questionId: q._id, content: "", time: 0
		}))
	}

	// onLoad(e) {
	// 	super.onLoad(e);
	//
	// 	//模拟数据请求
	// 	let list: Question[] = [];
	// 	for(let i=0; i<50;i++) {
	// 		let item: Question = new Question();
	// 		item.index = i;
	// 		item.type = 0;
	// 		item.title = i % 2 == 0 ? "某人在高h处抛出一个质量为m的物体.不计" +
	// 			"空气阻力，物体落地时的速度是v，则人对物体做的功是________" :
	// 			"请简述曲线曲面积分的几种方法";
	// 		list.push(item);
	// 		this.data.resultList[i] = null;
	// 	}
	// 	this.setData({quesList: list});
	// }

	/**
	 * 保存当前结果
	 * mode表示保存时的情况，1表示跳转下一页，-1表示跳转上一页，0表示通过答题卡跳转
	 * index表示通过答题卡跳转时的目标页
	 */
	private async saveAndJump(mode: number, index?: number) {
		await this.saveCurResult();
		await this.jump(mode, index);
	}
	private async saveCurResult() {
		const idx = this.data.currentIndex;
		this.data.quesRecords[idx].content =
			this.callPage.data.currentResult;

		await this.setData({
			quesRecords: this.data.quesRecords
		});
	}
	private async jump(mode: number, index?: number) {
		const idx = this.data.currentIndex;
		const tIdx = index || idx + mode;

		await this.setData({
			currentResult: this.data.quesRecords[tIdx].content
		});
	}

	// region 事件

	/**
	 * 提交
	 */
	@pageFunc
	public onClickSubmit() {
		// 调起订阅消息请求界面
		wx.requestSubscribeMessage({
			tmplIds: [TemplateIds["考核结果通知"]],
		}).finally(() => {
			this.submit();
		})
	}
	@handleError
	async submit() {
		await this.saveCurResult();
		await ExamInterface.FinishExam({
			examRecordId: this.params.examRecordId,
			quesRecords: this.data.quesRecords
		});

		await alertMgr().showAlert(
			"答题结果已提交！请耐心等待批改结果！"
		);
		this.back();
	}

	/**
	 * 打开弹窗
	 */
	@pageFunc
	public showPopup() {
		this.setData({ show: true });
	}

	/**
	 * 关闭弹窗
	 */
	@pageFunc
	public onClosePopup() {
		this.setData({ show: false });
	}

	/**
	 * 点击答题卡中的某一项进行跳转
	 */
	@pageFunc
	public async onClickCardItem(e) {
		let targetIndex: number = e.currentTarget.dataset.index;
		await this.saveAndJump(0, targetIndex);
		await this.setData({ currentIndex: targetIndex });
	}

	/**
	 * 下一题
	 */
	@pageFunc
	public async onClickNextQues() {
		if (this.data.currentIndex < this.data.item.quesCount - 1) {
			await this.saveAndJump(1);
			await this.setData({ currentIndex: this.data.currentIndex + 1 });
		}
	}

	/**
	 * 上一题
	 */
	@pageFunc
	public async onClickLastQues() {
		if (this.data.currentIndex > 0) {
			await this.saveAndJump(-1);
			await this.setData({ currentIndex: this.data.currentIndex - 1 });
		}
	}

	// endregion

}
